package com.ssm.dao;

import com.ssm.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestUserMapper {

    public UserMapper userMapper;

    @Before
    public void setUp() throws IOException {
        //指定配置文件
        String resource = "test/mybatis-config.xml";
        //读取配置文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //构建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        // 1. 映射文件的命名空间（namespace）必须是mapper接口的全路径
        // 2. 映射文件的statement的id必须和mapper接口的方法名保持一致
        // 3. Statement的resultType必须和mapper接口方法的返回类型一致
        // 4. statement的parameterType必须和mapper接口方法的参数类型一致（不一定）
        this.userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void testQueryUserById(){
        Integer id = 1;
        System.out.println(this.userMapper.queryUserById(id));
    }

    @Test
    public void tesInsertUser(){
        User user = new User();
        user.setName("test");
        user.setMoney(400d);
        this.userMapper.insertUser(user);
        System.out.println(user.getId());
    }

    @Test
    public void testFindAllUser(){
        List<User> users = this.userMapper.findAllUser();
        System.out.println(users.toString());
    }
}
